﻿// // ******************************************************************
// //       /\ /|       @file       JellyfinHelper.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-11 19:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-10 15:11 Await
// // ******************************************************************

using AutomaticSubtitles.Contracts.Dto.Jellyfin;
using AutomaticSubtitles.Contracts.Vo.Jellyfin;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

public static class JellyfinHelper
{
    /// <summary>
    /// 获取token
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public static Dictionary<string, string> GetToken(string? token)
    {
        if (token.IsNullOrWhiteSpace()) return new Dictionary<string, string>();
        var dictionary = new Dictionary<string, string>
        {
            // { "Authorization", token }
            { "X-MediaBrowser-Token", token }
        };
        return dictionary;
    }

    /// <summary>
    /// 登录系统
    /// </summary>
    /// <param name="data"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    public static async Task<JellyfinAuthEnticationDto?> Authenticatebyname(IHttpClientFactory httpClientFactory, AuthenticatebynameVo data, string url, string? token = "")
    {
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinAuthEnticationDto>(GetToken(token), $"{url.AutoPaseUrl()}Users/AuthenticateByName", data,
            GlobalVariableEnumConfiguration.RequestTypeEnum.post);
        return serviceBasicData;
    }

    /// <summary>
    /// 登录系统
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    public static async Task<JellyfinUserDto?> GetUser(IHttpClientFactory httpClientFactory, string userId, string url)
    {
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinUserDto>(null, $"{url.AutoPaseUrl()}Users/{userId}");
        return serviceBasicData;
    }

    /// <summary>
    /// 获取视频列表
    /// </summary>
    /// <param name="httpClientFactory"></param>
    /// <param name="token"></param>
    /// <param name="userId"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    public static async Task<JellyfinUserViewsDto?> UserViews(IHttpClientFactory httpClientFactory, string token, string userId, string url)
    {
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinUserViewsDto>(
            GetToken(token), 
            $"{url.AutoPaseUrl()}Users/{userId}/Views"
        );
        return serviceBasicData;
    }

    public static async Task<JellyfinItemsDto?> GetItems(IHttpClientFactory httpClientFactory, string token, string userId, string url)
    {
        var queryParams = new Dictionary<string, string>
        {
            ["UserId"] = userId,
            ["Fields"] = "Path,Overview,MediaSources",
            ["ImageTypeLimit"] = "1",
            ["EnableImageTypes"] = "Primary,Backdrop,Thumb",
            ["Recursive"] = "true"
        };

        var queryString = string.Join("&", queryParams.Select(x => $"{x.Key}={x.Value}"));
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinItemsDto>(
            GetToken(token),
            $"{url.AutoPaseUrl()}Users/{userId}/Items?{queryString}"
        );
        return serviceBasicData;
    }

    public static async Task<JellyfinItemsDto?> GetUserViews(IHttpClientFactory httpClientFactory, string id, string url)
    {
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinItemsDto>(null, $"{url.AutoPaseUrl()}Users/{id}/Views");
        return serviceBasicData;
    }

    public static async Task<JellyfinItemDetailDto?> GetItemDetail(IHttpClientFactory httpClientFactory, string token, string id, string url)
    {
        var queryParams = new Dictionary<string, string>
        {
            ["Fields"] = "Path,Overview,MediaSources,Width,Height,Chapters",
            ["EnableImages"] = "true",
            ["ImageTypeLimit"] = "1",
            ["EnableImageTypes"] = "Primary,Backdrop,Thumb"
        };

        var queryString = string.Join("&", queryParams.Select(x => $"{x.Key}={x.Value}"));
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinItemDetailDto>(
            GetToken(token),
            $"{url.AutoPaseUrl()}Users/{id}/Items/{id}?{queryString}"
        );
        return serviceBasicData;
    }

    public static async Task<Stream?> GetStream(IHttpClientFactory httpClientFactory, string token, string id, string url)
    {
        var client = httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("X-MediaBrowser-Token", token);
        
        var queryParams = new Dictionary<string, string>
        {
            ["Static"] = "true",
            ["MediaSourceId"] = id,
            ["VideoCodec"] = "h264",
            ["AudioCodec"] = "aac",
            ["MaxAudioChannels"] = "2"
        };

        var queryString = string.Join("&", queryParams.Select(x => $"{x.Key}={x.Value}"));
        var response = await client.GetAsync($"{url.AutoPaseUrl()}Videos/{id}/stream.mp4?{queryString}");
        return await response.Content.ReadAsStreamAsync();
    }

    public static async Task<JellyfinItemsDto?> GetChildren(IHttpClientFactory httpClientFactory, string token, string id, string url)
    {
        var serviceBasicData = await httpClientFactory.GetServiceBasicData<JellyfinItemsDto>(
            GetToken(token), 
            $"{url.AutoPaseUrl()}Items/{id}/Children?Fields=Path,Overview,MediaSources,Width,Height"
        );
        return serviceBasicData;
    }
}